<template>
  <div id="wx-open-qrcode" class="mt-1">
    <iframe ref="iframe"
            :src="src"
            frameborder="0"
            scrolling="no">
    </iframe>
    <div class="text-center mt-2 text-slate-500">使用微信扫一扫登录</div>
  </div>

  <a-modal v-model:visible="bindingModalVisible"
           :footer="null"
           title="绑定账号"
           @cancel="handleBindingModalCancel">
    <a-alert class="mb-2" description="您的微信号还未绑定任何账号，请先进行绑定 ~"/>
    <a-tabs v-model:active-key="activeKey">
      <a-tab-pane key="smsCode">
        <template #tab>
          <mobile-two-tone/>
          短信验证码
        </template>
        <login-sms-code :extra-params="{ bindingToken }" login-button-text="登录并绑定"/>
      </a-tab-pane>
      <a-tab-pane key="password">
        <template #tab>
          <lock-two-tone/>
          密码登录
        </template>
        <login-password :extra-params="{ bindingToken }" login-button-text="登录并绑定"/>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script setup>
import qs from "qs";
import {LockTwoTone, MobileTwoTone} from "@ant-design/icons-vue";
import LoginSmsCode from "./login-sms-code.vue";
import LoginPassword from "./login-password.vue";

const iframe = ref();

const src = 'https://open.weixin.qq.com/connect/qrconnect?' + qs.stringify({
  appid: 'wx0f2aff39bfa8a213',
  scope: 'snsapi_login',
  redirect_uri: `${window.location.origin}/login/wx-open`,
  state: 'state',
  login_type: 'jssdk',
  self_redirect: true,
  href: 'data:text/css;base64,LnRpdGxle2Rpc3BsYXk6bm9uZX0uaW1wb3dlckJveCAucXJjb2Rle21hcmdpbi10b3A6MDtib3JkZXI6MXB4IHNvbGlkICNlMmU4ZjB9I3d4X2RlZmF1bHRfdGlwe2Rpc3BsYXk6bm9uZX0jd3hfYWZ0ZXJfc2Nhbntwb3NpdGlvbjpmaXhlZDtsZWZ0OjFweDtib3R0b206MXB4O3dpZHRoOjI1MnB4O2JhY2tncm91bmQ6I2YwZmVmN30='
});

const activeKey = ref('smsCode');

const bindingModalVisible = ref(false);

const bindingToken = ref(null);
const router = useRouter();
const receiveMessage = (event) => {
  const {type, binding, token} = event.data;
  if (type !== 'wx-open-login') {
    return;
  }
  // 已经绑定用户
  if (binding) {
    router.replace('/');
    return;
  }
  bindingModalVisible.value = true;
  bindingToken.value = token;
};

const handleBindingModalCancel = () => {
  iframe.value.src = iframe.value.src + '';
}

onMounted(() => {
  window.addEventListener('message', receiveMessage);
});

onBeforeUnmount(() => {
  window.removeEventListener('message', receiveMessage);
});
</script>
<style scoped>
#wx-open-qrcode {
  text-align: center;
}

iframe {
  width: 282px;
  height: 282px;
  box-sizing: content-box;
}
</style>
